package com.why.zing.idgenerator.provider;


import com.why.zing.idgenerator.utils.IpUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class IpConfigurableMachineIdProvider implements MachineIdProvider {

    private long machineId;

    private Map<String, Long> ipsMap = new HashMap<>();

    public IpConfigurableMachineIdProvider() {
    }

    public IpConfigurableMachineIdProvider(String ips) {
        setIps(ips);
        init();
    }

    public void init() {
        String ip = IpUtils.getHostIp();

        if (StringUtils.isEmpty(ip)) {
            throw new IllegalStateException("Fail to get host IP address. Stop to initialize the IpConfigurableMachineIdProvider provider");
        }

        if (!ipsMap.containsKey(ip)) {
            String msg = String
                    .format("Fail to configure ID for host IP address %s. Stop to initialize the IpConfigurableMachineIdProvider provider.",
                            ip);
            throw new IllegalStateException(msg);
        }
        machineId = ipsMap.get(ip);

    }

    public void setIps(String ips) {
        if (!StringUtils.isEmpty(ips)) {
            String[] ipArray = ips.split(",");

            for (int i = 0; i < ipArray.length; i++) {
                ipsMap.put(ipArray[i], (long) i);
            }
        }
    }

    @Override
    public long getMachineId() {
        return machineId;
    }

    public void setMachineId(long machineId) {
        this.machineId = machineId;
    }
}
